package com.xzzz.irda.guardcat.server.alert.listener;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.irda.guardcat.core.pojo.Alert;
import com.xzzz.irda.guardcat.server.alert.AlertListener;
import com.xzzz.irda.guardcat.server.util.PhoneMsgUtil;
import com.xzzz.irda.guardcat.server.setting.AlertSetting;
import lombok.extern.slf4j.Slf4j;

/**
 * 警告监听,发送手机短信
 * @author xzzz
 */
@Slf4j
public class AlertPhoneMsgListener {

    @AlertListener
    public void handle(Alert alert, AlertSetting alertSetting) {
        String[] phones = getPhones(alert, alertSetting);
        if (ArrayUtil.isEmpty(phones)) {
            return;
        }

        for (final String phone : phones) {
            if (phone.length() != 11) {
                continue;
            }

            log.info("发布警告短信: {} > {}", alert.getTitle(), phone);

            PhoneMsgUtil.PhoneMsg phoneMsg = new PhoneMsgUtil.PhoneMsg();
            phoneMsg.setReceiverPhone(phone);
            phoneMsg.setId(alert.getId());
            phoneMsg.setTemplate("SMS_235495483");
            phoneMsg.setContent(
            "{" +
                "\"system\":\"" + alert.getAppName() + "\"," +
                "\"type\":\"" + alert.getTitle() + "\"" +
            "}");
            try {
                PhoneMsgUtil.send(phoneMsg);
            } catch (Throwable e) {
                e.printStackTrace();
                log.error("发送短信失败,警告: {}, 配置: {}, 异常: {}", alert.toString(), phone, e.getMessage());
            }
        }
    }

    private String[] getPhones(Alert alert, AlertSetting alertSetting) {
        String[] phones = new String[0];

        // 如果配置了警告渠道, 则使用
        if (alertSetting != null && StrUtil.isNotBlank(alertSetting.getPhone())) {
            phones = alertSetting.getPhone().split(",");
        }

        // 如果消息中包含手机号, 则使用消息中的
        if (alert.getPhone() != null) {
            phones = alert.getPhone().split(",");
        }
        return phones;
    }
}
